package com.ruoyi.web.controller.credit;

import java.util.*;
import java.util.Arrays;
import java.math.BigDecimal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.CreditUserInfo;
import com.ruoyi.system.domain.CreditRecycleRecord;
import com.ruoyi.system.domain.CreditRecycleStation;
import com.ruoyi.system.domain.CreditWaterActivity;
import com.ruoyi.system.domain.CreditCharityActivity;
import com.ruoyi.system.domain.CreditProsocialStats;
import com.ruoyi.system.domain.CreditWaterStation;
import com.ruoyi.system.domain.CreditWaterActivityParticipant;
import com.ruoyi.system.domain.CreditCharityActivityParticipant;
import com.ruoyi.system.service.ICreditUserInfoService;
import com.ruoyi.system.service.ICreditRecycleRecordService;
import com.ruoyi.system.service.ICreditRecycleStationService;
import com.ruoyi.system.service.ICreditWaterActivityService;
import com.ruoyi.system.service.ICreditCharityActivityService;
import com.ruoyi.system.service.ICreditProsocialStatsService;
import com.ruoyi.system.service.ICreditWaterStationService;
import com.ruoyi.system.service.ICreditWaterActivityParticipantService;
import com.ruoyi.system.service.ICreditCharityActivityParticipantService;

/**
 * 亲社会行为控制器
 * 
 * @author ruoyi
 * @date 2024-01-26
 */
@RestController
@RequestMapping("/credit/prosocial")
public class CreditProsocialController extends BaseController
{
    private static final Logger logger = LoggerFactory.getLogger(CreditProsocialController.class);
    
    @Autowired
    private ICreditUserInfoService creditUserInfoService;
    
    @Autowired
    private ICreditRecycleRecordService creditRecycleRecordService;
    
    @Autowired
    private ICreditRecycleStationService creditRecycleStationService;
    
    @Autowired
    private ICreditWaterActivityService creditWaterActivityService;
    
    @Autowired
    private ICreditCharityActivityService creditCharityActivityService;
    
    @Autowired
    private ICreditProsocialStatsService creditProsocialStatsService;
    
    @Autowired
    private ICreditWaterStationService creditWaterStationService;
    
    @Autowired
    private ICreditWaterActivityParticipantService creditWaterActivityParticipantService;
    
    @Autowired
    private ICreditCharityActivityParticipantService creditCharityActivityParticipantService;

    /**
     * 获取用户信用信息和月度统计
     */
    @PreAuthorize("@ss.hasPermi('credit:prosocial:view')")
    @GetMapping("/userStats")
    public AjaxResult getUserStats()
    {
        Long userId = getUserId();
        CreditProsocialStats stats = creditProsocialStatsService.selectCreditProsocialStatsByUserId(userId);
        // 获取用户真实信用分
        CreditUserInfo userInfo = creditUserInfoService.selectCreditUserInfoByUserId(userId);
        Integer realCreditScore = userInfo != null ? userInfo.getCreditScore() : null;
        String realCreditLevel = "未知";
        if (realCreditScore != null) {
            if (realCreditScore >= 800) realCreditLevel = "优秀";
            else if (realCreditScore >= 750) realCreditLevel = "良好";
            else if (realCreditScore >= 700) realCreditLevel = "一般";
            else realCreditLevel = "较低";
        }
        Map<String, Object> userStats = new HashMap<>();
        if (stats != null) {
            userStats.put("creditScore", realCreditScore != null ? realCreditScore : 750);
            userStats.put("creditLevel", realCreditLevel);
            userStats.put("monthlyGrowth", 12);
            userStats.put("totalActivities", stats.getTotalRecycleCount() + stats.getTotalWaterActivities() + stats.getTotalCharityActivities());
            userStats.put("totalPoints", stats.getTotalRecycleScore() + stats.getTotalWaterScore() + stats.getTotalCharityScore());
            userStats.put("ranking", 156);
            // 回收统计
            userStats.put("totalRecycleCount", stats.getTotalRecycleCount());
            userStats.put("totalRecycleScore", stats.getTotalRecycleScore());
            userStats.put("totalRecycleWeight", stats.getTotalRecycleWeight());
            userStats.put("carbonReduction", stats.getCarbonReduction());
            // 护水统计
            userStats.put("totalWaterActivities", stats.getTotalWaterActivities());
            userStats.put("totalWaterScore", stats.getTotalWaterScore());
            userStats.put("protectedWaterVolume", stats.getProtectedWaterVolume());
            userStats.put("cleanedArea", stats.getCleanedArea());
            // 公益统计
            userStats.put("totalCharityActivities", stats.getTotalCharityActivities());
            userStats.put("totalCharityScore", stats.getTotalCharityScore());
            userStats.put("totalVolunteerHours", stats.getTotalVolunteerHours());
            userStats.put("totalDonationAmount", stats.getTotalDonationAmount());
            userStats.put("charityLevel", stats.getCharityLevel());
            userStats.put("charityPoints", stats.getCharityPoints());
        } else {
            userStats.put("creditScore", realCreditScore != null ? realCreditScore : 750);
            userStats.put("creditLevel", realCreditLevel);
            userStats.put("monthlyGrowth", 0);
            userStats.put("totalActivities", 0);
            userStats.put("totalPoints", 0);
            userStats.put("ranking", 0);
            userStats.put("totalRecycleCount", 0);
            userStats.put("totalRecycleScore", 0);
            userStats.put("totalRecycleWeight", 0);
            userStats.put("carbonReduction", 0);
            userStats.put("totalWaterActivities", 0);
            userStats.put("totalWaterScore", 0);
            userStats.put("protectedWaterVolume", 0);
            userStats.put("cleanedArea", 0);
            userStats.put("totalCharityActivities", 0);
            userStats.put("totalCharityScore", 0);
            userStats.put("totalVolunteerHours", 0);
            userStats.put("totalDonationAmount", 0);
            userStats.put("charityLevel", 1);
            userStats.put("charityPoints", 0);
        }
        // 月度增长趋势（这里可以查询历史数据）
        List<Map<String, Object>> monthlyTrend = new ArrayList<>();
        monthlyTrend.add(createMonthlyPoint("1月1日", 5));
        monthlyTrend.add(createMonthlyPoint("1月8日", 8));
        monthlyTrend.add(createMonthlyPoint("1月15日", 12));
        monthlyTrend.add(createMonthlyPoint("1月22日", 7));
        monthlyTrend.add(createMonthlyPoint("1月29日", 10));
        userStats.put("monthlyTrend", monthlyTrend);
        return AjaxResult.success(userStats);
    }

    /**
     * 获取回收站点列表
     */
    @PreAuthorize("@ss.hasPermi('credit:prosocial:view')")
    @GetMapping("/recycle/stations")
    public AjaxResult getRecycleStations(@RequestParam(required = false) String area)
    {
        CreditRecycleStation queryStation = new CreditRecycleStation();
        queryStation.setIsAvailable("1");
        List<CreditRecycleStation> stations = creditRecycleStationService.selectCreditRecycleStationList(queryStation);
        
        List<Map<String, Object>> result = new ArrayList<>();
        for (CreditRecycleStation station : stations) {
            Map<String, Object> stationMap = new HashMap<>();
            stationMap.put("id", station.getStationId());
            stationMap.put("name", station.getStationName());
            stationMap.put("address", station.getStationAddress());
            stationMap.put("lat", station.getLatitude());
            stationMap.put("lng", station.getLongitude());
            stationMap.put("distance", "1.2km"); // 这里可以根据用户位置计算实际距离
            stationMap.put("types", parseRecycleTypes(station.getRecycleTypes()));
            stationMap.put("openTime", station.getOpenTime());
            stationMap.put("points", Arrays.asList(2, 3, 5, 10)); // 固定积分规则
            stationMap.put("phone", station.getPhone());
            result.add(stationMap);
        }
        
        return AjaxResult.success(result);
    }

    /**
     * 获取回收记录
     */
    @PreAuthorize("@ss.hasPermi('credit:prosocial:view')")
    @GetMapping("/recycle/records")
    public AjaxResult getRecycleRecords()
    {
        Long userId = getUserId();
        CreditRecycleRecord queryRecord = new CreditRecycleRecord();
        queryRecord.setUserId(userId);
        List<CreditRecycleRecord> records = creditRecycleRecordService.selectCreditRecycleRecordList(queryRecord);
        
        List<Map<String, Object>> result = new ArrayList<>();
        for (CreditRecycleRecord record : records) {
            Map<String, Object> recordMap = new HashMap<>();
            recordMap.put("id", record.getRecordId());
            recordMap.put("date", record.getCreateTime());
            recordMap.put("station", getStationName(record.getStationId()));
            recordMap.put("type", record.getRecycleType());
            recordMap.put("quantity", record.getQuantity());
            recordMap.put("unit", record.getUnit());
            recordMap.put("points", record.getPoints());
            recordMap.put("status", getStatusText(record.getStatus()));
            result.add(recordMap);
        }
        
        return AjaxResult.success(result);
    }

    /**
     * 提交回收记录
     */
    @PreAuthorize("@ss.hasPermi('credit:prosocial:view')")
    @Log(title = "资源回收提交", businessType = BusinessType.INSERT)
    @PostMapping("/recycle/submit")
    public AjaxResult submitRecycle(@RequestBody Map<String, Object> recycleData)
    {
        Long userId = getUserId();
        Integer stationId = (Integer) recycleData.get("stationId");
        String type = (String) recycleData.get("type");
        Double quantity = Double.valueOf(recycleData.get("quantity").toString());
        String remark = (String) recycleData.get("remark");
        
        // 计算积分
        int points = calculateRecyclePoints(type, quantity);
        
        // 创建回收记录
        CreditRecycleRecord record = new CreditRecycleRecord();
        record.setUserId(userId);
        record.setStationId(stationId.longValue());
        record.setRecycleType(type);
        record.setQuantity(new BigDecimal(quantity));
        record.setUnit(getUnitByType(type));
        record.setPoints(points);
        record.setCarbonReduction(calculateCarbonReduction(type, quantity));
        record.setStatus("confirmed"); // 直接设置为已确认
        record.setRemark(remark);
        record.setCreateBy(getUsername());
        
        int result = creditRecycleRecordService.insertCreditRecycleRecord(record);
        
        if (result > 0) {
            // 更新用户信用分
            CreditUserInfo userInfo = creditUserInfoService.selectCreditUserInfoByUserId(userId);
            if (userInfo != null) {
                Integer currentScore = userInfo.getCreditScore() != null ? userInfo.getCreditScore() : 600;
                Integer newScore = currentScore + points;
                creditUserInfoService.updateCreditScore(userId, newScore, "完成资源回收活动");
            }
            
            // 更新用户统计
            creditProsocialStatsService.updateRecycleStats(userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("recordId", record.getRecordId());
            response.put("points", points);
            response.put("status", "confirmed");
            response.put("message", "回收成功！获得" + points + "积分");
            
            return AjaxResult.success(response);
        } else {
            return AjaxResult.error("提交失败，请稍后重试");
        }
    }

    /**
     * 获取水质监测站点
     */
    @PreAuthorize("@ss.hasPermi('credit:prosocial:view')")
    @GetMapping("/water/stations")
    public AjaxResult getWaterStations()
    {
        CreditWaterStation queryStation = new CreditWaterStation();
        queryStation.setIsAvailable("1");
        List<CreditWaterStation> stations = creditWaterStationService.selectCreditWaterStationList(queryStation);
        
        List<Map<String, Object>> result = new ArrayList<>();
        for (CreditWaterStation station : stations) {
            Map<String, Object> stationMap = new HashMap<>();
            stationMap.put("id", station.getStationId());
            stationMap.put("name", station.getStationName());
            stationMap.put("location", station.getStationLocation());
            stationMap.put("lat", station.getLatitude());
            stationMap.put("lng", station.getLongitude());
            stationMap.put("quality", station.getWaterQuality());
            stationMap.put("qualityLevel", getQualityLevel(station.getWaterQuality()));
            stationMap.put("lastUpdate", station.getLastTestDate());
            stationMap.put("distance", "1.2km"); // 这里可以根据用户位置计算实际距离
            stationMap.put("canReport", true);
            result.add(stationMap);
        }
        
        return AjaxResult.success(result);
    }

    /**
     * 获取护水活动列表
     */
    @PreAuthorize("@ss.hasPermi('credit:prosocial:view')")
    @GetMapping("/water/activities")
    public AjaxResult getWaterActivities(@RequestParam(required = false) String type)
    {
        CreditWaterActivity queryActivity = new CreditWaterActivity();
        queryActivity.setIsAvailable("1");
        if (type != null && !type.isEmpty()) {
            queryActivity.setActivityType(type);
        }
        List<CreditWaterActivity> activities = creditWaterActivityService.selectCreditWaterActivityList(queryActivity);
        
        List<Map<String, Object>> result = new ArrayList<>();
        for (CreditWaterActivity activity : activities) {
            Map<String, Object> activityMap = new HashMap<>();
            activityMap.put("id", activity.getActivityId());
            activityMap.put("title", activity.getActivityTitle());
            activityMap.put("type", activity.getActivityType());
            activityMap.put("date", activity.getActivityDate());
            activityMap.put("location", activity.getActivityLocation());
            activityMap.put("description", activity.getActivityDescription());
            activityMap.put("participants", activity.getCurrentParticipants());
            activityMap.put("maxParticipants", activity.getMaxParticipants());
            activityMap.put("points", activity.getPointsReward());
            activityMap.put("duration", activity.getDuration());
            activityMap.put("organizer", activity.getOrganizer());
            activityMap.put("requirements", activity.getRequirements());
            activityMap.put("status", getActivityStatusText(activity.getStatus()));
            activityMap.put("canJoin", "recruiting".equals(activity.getStatus()));
            result.add(activityMap);
        }
        
        return AjaxResult.success(result);
    }

    /**
     * 获取公益活动列表
     */
    @PreAuthorize("@ss.hasPermi('credit:prosocial:view')")
    @GetMapping("/charity/activities")
    public AjaxResult getCharityActivities(@RequestParam(required = false) String category)
    {
        CreditCharityActivity queryActivity = new CreditCharityActivity();
        queryActivity.setIsAvailable("1");
        if (category != null && !category.isEmpty()) {
            queryActivity.setActivityCategory(category);
        }
        List<CreditCharityActivity> activities = creditCharityActivityService.selectCreditCharityActivityList(queryActivity);
        
        List<Map<String, Object>> result = new ArrayList<>();
        for (CreditCharityActivity activity : activities) {
            Map<String, Object> activityMap = new HashMap<>();
            activityMap.put("id", activity.getActivityId());
            activityMap.put("title", activity.getActivityTitle());
            activityMap.put("category", activity.getActivityCategory());
            activityMap.put("date", activity.getActivityDate());
            activityMap.put("location", activity.getActivityLocation());
            activityMap.put("description", activity.getActivityDescription());
            activityMap.put("participants", activity.getCurrentParticipants());
            activityMap.put("maxParticipants", activity.getMaxParticipants());
            activityMap.put("points", activity.getPointsReward());
            activityMap.put("duration", activity.getDuration());
            activityMap.put("organizer", activity.getOrganizer());
            activityMap.put("requirements", activity.getRequirements());
            activityMap.put("status", getActivityStatusText(activity.getStatus()));
            activityMap.put("canJoin", "recruiting".equals(activity.getStatus()));
            result.add(activityMap);
        }
        
        return AjaxResult.success(result);
    }

    /**
     * 获取用户护水记录
     */
    @PreAuthorize("@ss.hasPermi('credit:prosocial:view')")
    @GetMapping("/water/records")
    public AjaxResult getWaterRecords()
    {
        Long userId = getUserId();
        CreditWaterActivityParticipant queryParticipant = new CreditWaterActivityParticipant();
        queryParticipant.setUserId(userId);
        List<CreditWaterActivityParticipant> participants = creditWaterActivityParticipantService.selectCreditWaterActivityParticipantList(queryParticipant);
        
        List<Map<String, Object>> result = new ArrayList<>();
        for (CreditWaterActivityParticipant participant : participants) {
            Map<String, Object> recordMap = new HashMap<>();
            recordMap.put("id", participant.getParticipantId());
            recordMap.put("date", participant.getParticipationDate());
            recordMap.put("activity", getWaterActivityTitle(participant.getActivityId()));
            recordMap.put("type", getWaterActivityType(participant.getActivityId()));
            recordMap.put("points", participant.getPointsEarned());
            recordMap.put("duration", participant.getActualDuration() != null ? participant.getActualDuration() + "小时" : "未知");
            recordMap.put("contribution", participant.getContribution());
            recordMap.put("status", getStatusText(participant.getStatus()));
            result.add(recordMap);
        }
        
        return AjaxResult.success(result);
    }

    /**
     * 获取公益记录
     */
    @PreAuthorize("@ss.hasPermi('credit:prosocial:view')")
    @GetMapping("/charity/records")
    public AjaxResult getCharityRecords()
    {
        Long userId = getUserId();
        CreditCharityActivityParticipant queryParticipant = new CreditCharityActivityParticipant();
        queryParticipant.setUserId(userId);
        List<CreditCharityActivityParticipant> participants = creditCharityActivityParticipantService.selectCreditCharityActivityParticipantList(queryParticipant);
        
        List<Map<String, Object>> result = new ArrayList<>();
        for (CreditCharityActivityParticipant participant : participants) {
            Map<String, Object> recordMap = new HashMap<>();
            recordMap.put("id", participant.getParticipantId());
            recordMap.put("date", participant.getParticipationDate());
            recordMap.put("activity", getCharityActivityTitle(participant.getActivityId()));
            recordMap.put("category", getCharityActivityCategory(participant.getActivityId()));
            recordMap.put("points", participant.getPointsEarned());
            recordMap.put("hours", participant.getActualDuration());
            recordMap.put("contribution", participant.getContribution());
            recordMap.put("donationAmount", participant.getDonationAmount());
            recordMap.put("status", getStatusText(participant.getStatus()));
            result.add(recordMap);
        }
        
        return AjaxResult.success(result);
    }

    /**
     * 获取用户公益等级信息
     */
    @PreAuthorize("@ss.hasPermi('credit:prosocial:view')")
    @GetMapping("/charity/level")
    public AjaxResult getCharityLevel()
    {
        Map<String, Object> levelInfo = new HashMap<>();
        levelInfo.put("currentLevel", 3);
        levelInfo.put("levelName", "公益达人");
        levelInfo.put("currentPoints", 420);
        levelInfo.put("nextLevelPoints", 500);
        levelInfo.put("progress", 84); // (420/500)*100
        levelInfo.put("totalActivities", 28);
        levelInfo.put("volunteerHours", 56);
        levelInfo.put("donationAmount", 800);
        
        // 等级说明
        List<Map<String, Object>> levels = new ArrayList<>();
        levels.add(createLevel(1, "爱心新手", 0, 100));
        levels.add(createLevel(2, "公益助手", 100, 250));
        levels.add(createLevel(3, "公益达人", 250, 500));
        levels.add(createLevel(4, "公益专家", 500, 1000));
        levels.add(createLevel(5, "公益之星", 1000, 99999));
        levelInfo.put("levels", levels);
        
        return AjaxResult.success(levelInfo);
    }

    /**
     * 参加活动
     */
    @PreAuthorize("@ss.hasPermi('credit:prosocial:view')")
    @Log(title = "参加活动", businessType = BusinessType.INSERT)
    @PostMapping("/activities/join")
    public AjaxResult joinActivity(@RequestBody Map<String, Object> joinData)
    {
        Long userId = getUserId();
        Integer activityId = (Integer) joinData.get("activityId");
        String activityType = (String) joinData.get("activityType");
        
        logger.info("用户报名参加活动，用户ID：{}，活动ID：{}，类型：{}", userId, activityId, activityType);
        
        try {
            if ("water".equals(activityType)) {
                // 参与护水活动
                CreditWaterActivity waterActivity = creditWaterActivityService.selectCreditWaterActivityByActivityId(activityId.longValue());
                if (waterActivity == null) {
                    return AjaxResult.error("活动不存在");
                }
                
                // 创建参与记录
                CreditWaterActivityParticipant participant = new CreditWaterActivityParticipant();
                participant.setUserId(userId);
                participant.setActivityId(activityId.longValue());
                participant.setParticipationDate(new Date());
                participant.setStatus("confirmed");
                participant.setPointsEarned(waterActivity.getPointsReward());
                String durationStr = waterActivity.getDuration();
                if (durationStr != null && !durationStr.trim().isEmpty()) {
                    try {
                        participant.setActualDuration(new BigDecimal(durationStr.trim()));
                    } catch (Exception e) {
                        participant.setActualDuration(BigDecimal.ZERO);
                    }
                } else {
                    participant.setActualDuration(BigDecimal.ZERO);
                }
                participant.setContribution("参与" + waterActivity.getActivityTitle());
                participant.setCreateBy(getUsername());
                
                int result = creditWaterActivityParticipantService.insertCreditWaterActivityParticipant(participant);
                
                if (result > 0) {
                    // 更新用户信用分
                    CreditUserInfo userInfo = creditUserInfoService.selectCreditUserInfoByUserId(userId);
                    if (userInfo != null) {
                        Integer currentScore = userInfo.getCreditScore() != null ? userInfo.getCreditScore() : 600;
                        Integer newScore = currentScore + waterActivity.getPointsReward();
                        creditUserInfoService.updateCreditScore(userId, newScore, "完成护水活动");
                    }
                    
                    // 更新统计
                    creditProsocialStatsService.updateWaterStats(userId);
                    
                    Map<String, Object> response = new HashMap<>();
                    response.put("registrationId", participant.getParticipantId());
                    response.put("status", "confirmed");
                    response.put("points", waterActivity.getPointsReward());
                    response.put("message", "护水活动参与成功！获得" + waterActivity.getPointsReward() + "积分");
                    
                    return AjaxResult.success(response);
                }
            } else if ("charity".equals(activityType)) {
                // 参与公益活动
                CreditCharityActivity charityActivity = creditCharityActivityService.selectCreditCharityActivityByActivityId(activityId.longValue());
                if (charityActivity == null) {
                    return AjaxResult.error("活动不存在");
                }
                
                // 创建参与记录
                CreditCharityActivityParticipant participant = new CreditCharityActivityParticipant();
                participant.setUserId(userId);
                participant.setActivityId(activityId.longValue());
                participant.setParticipationDate(new Date());
                participant.setStatus("confirmed");
                participant.setPointsEarned(charityActivity.getPointsReward());
                String durationStr = charityActivity.getDuration();
                if (durationStr != null && !durationStr.trim().isEmpty()) {
                    try {
                        participant.setActualDuration(new BigDecimal(durationStr.trim()));
                    } catch (Exception e) {
                        participant.setActualDuration(BigDecimal.ZERO);
                    }
                } else {
                    participant.setActualDuration(BigDecimal.ZERO);
                }
                participant.setContribution("参与" + charityActivity.getActivityTitle());
                Object donationAmountObj = joinData.get("donationAmount");
                if (donationAmountObj instanceof BigDecimal) {
                    participant.setDonationAmount((BigDecimal) donationAmountObj);
                } else if (donationAmountObj instanceof Number) {
                    participant.setDonationAmount(BigDecimal.valueOf(((Number) donationAmountObj).doubleValue()));
                } else if (donationAmountObj instanceof String && !((String)donationAmountObj).trim().isEmpty()) {
                    try {
                        participant.setDonationAmount(new BigDecimal((String)donationAmountObj));
                    } catch (Exception e) {
                        participant.setDonationAmount(BigDecimal.ZERO);
                    }
                } else {
                    participant.setDonationAmount(BigDecimal.ZERO);
                }
                participant.setCreateBy(getUsername());
                
                int result = creditCharityActivityParticipantService.insertCreditCharityActivityParticipant(participant);
                
                if (result > 0) {
                    // 更新用户信用分
                    CreditUserInfo userInfo = creditUserInfoService.selectCreditUserInfoByUserId(userId);
                    if (userInfo != null) {
                        Integer currentScore = userInfo.getCreditScore() != null ? userInfo.getCreditScore() : 600;
                        Integer newScore = currentScore + charityActivity.getPointsReward();
                        creditUserInfoService.updateCreditScore(userId, newScore, "完成公益活动");
                    }
                    
                    // 更新统计
                    creditProsocialStatsService.updateCharityStats(userId);
                    
                    Map<String, Object> response = new HashMap<>();
                    response.put("registrationId", participant.getParticipantId());
                    response.put("status", "confirmed");
                    response.put("points", charityActivity.getPointsReward());
                    response.put("message", "公益活动参与成功！获得" + charityActivity.getPointsReward() + "积分");
                    
                    return AjaxResult.success(response);
                }
            }
            
            return AjaxResult.error("参与失败，请稍后重试");
            
        } catch (Exception e) {
            logger.error("参与活动失败", e);
            return AjaxResult.error("参与失败：" + e.getMessage());
        }
    }

    /**
     * 上报水质问题
     */
    @PreAuthorize("@ss.hasPermi('credit:prosocial:view')")
    @Log(title = "水质问题上报", businessType = BusinessType.INSERT)
    @PostMapping("/water/report")
    public AjaxResult reportWaterIssue(@RequestBody Map<String, Object> reportData)
    {
        Long userId = getUserId();
        Integer stationId = (Integer) reportData.get("stationId");
        String issueType = (String) reportData.get("issueType");
        String description = (String) reportData.get("description");
        String urgency = (String) reportData.get("urgency");
        
        logger.info("用户上报水质问题，用户ID：{}，站点ID：{}，问题类型：{}，描述：{}", 
                   userId, stationId, issueType, description);
        
        try {
            // 这里应该创建水质问题上报记录表，暂时用日志记录
            // 计算积分奖励
            int points = 10; // 基础积分
            if ("紧急".equals(urgency)) {
                points = 15;
            } else if ("非常紧急".equals(urgency)) {
                points = 20;
            }
            
            // 更新用户信用分
            CreditUserInfo userInfo = creditUserInfoService.selectCreditUserInfoByUserId(userId);
            if (userInfo != null) {
                Integer currentScore = userInfo.getCreditScore() != null ? userInfo.getCreditScore() : 600;
                Integer newScore = currentScore + points;
                creditUserInfoService.updateCreditScore(userId, newScore, "上报水质问题");
            }
        
        Map<String, Object> result = new HashMap<>();
        result.put("reportId", "WR" + System.currentTimeMillis());
            result.put("points", points);
        result.put("status", "submitted");
            result.put("message", "感谢您的上报！相关部门将及时处理，您将获得" + points + "积分奖励");
        
        return AjaxResult.success(result);
            
        } catch (Exception e) {
            logger.error("上报水质问题失败", e);
            return AjaxResult.error("上报失败：" + e.getMessage());
        }
    }

    // 辅助方法
    private Map<String, Object> createMonthlyPoint(String date, Integer points) {
        Map<String, Object> point = new HashMap<>();
        point.put("date", date);
        point.put("points", points);
        return point;
    }

    private Map<String, Object> createLevel(Integer level, String name, Integer minPoints, Integer maxPoints) {
        Map<String, Object> levelData = new HashMap<>();
        levelData.put("level", level);
        levelData.put("name", name);
        levelData.put("minPoints", minPoints);
        levelData.put("maxPoints", maxPoints);
        return levelData;
    }

    private int calculateRecyclePoints(String type, Double weight) {
        int basePoints = 2; // 基础积分
        switch (type) {
            case "纸类":
                return (int) (basePoints * weight);
            case "塑料":
                return (int) (basePoints * weight * 1.5);
            case "金属":
                return (int) (basePoints * weight * 2.5);
            case "玻璃":
                return (int) (basePoints * weight * 2);
            case "电子":
                return (int) (basePoints * weight * 5);
            default:
                return basePoints;
        }
    }

    /**
     * 解析回收类型JSON字符串
     */
    private List<String> parseRecycleTypes(String recycleTypes) {
        try {
            // 这里可以使用JSON解析库，暂时返回固定值
            return Arrays.asList("纸类", "塑料", "金属", "电子");
        } catch (Exception e) {
            return Arrays.asList("纸类", "塑料");
        }
    }
    
    /**
     * 根据类型获取单位
     */
    private String getUnitByType(String type) {
        switch (type) {
            case "塑料瓶":
            case "废电池":
            case "电子产品":
                return "个";
            case "废纸":
            case "金属":
            case "玻璃":
                return "kg";
            default:
                return "kg";
        }
    }
    
    /**
     * 计算碳减排量
     */
    private BigDecimal calculateCarbonReduction(String type, Double weight) {
        double factor = 0.5; // 默认系数
        switch (type) {
            case "废纸":
                factor = 0.5;
                break;
            case "塑料":
                factor = 0.5;
                break;
            case "金属":
                factor = 0.5;
                break;
            case "电子产品":
                factor = 5.0;
                break;
            case "废电池":
                factor = 0.2;
                break;
        }
        return new BigDecimal(weight * factor);
    }
    
    /**
     * 获取站点名称
     */
    private String getStationName(Long stationId) {
        CreditRecycleStation station = creditRecycleStationService.selectCreditRecycleStationByStationId(stationId);
        return station != null ? station.getStationName() : "未知站点";
    }
    
    /**
     * 获取状态文本
     */
    private String getStatusText(String status) {
        switch (status) {
            case "pending":
                return "待确认";
            case "confirmed":
                return "已确认";
            case "rejected":
                return "已拒绝";
            default:
                return status;
        }
    }
    
    /**
     * 获取活动状态文本
     */
    private String getActivityStatusText(String status) {
        switch (status) {
            case "recruiting":
                return "报名中";
            case "ongoing":
                return "进行中";
            case "completed":
                return "已结束";
            default:
                return status;
        }
    }

    // ======================== 普通用户专用接口（无权限） ========================

    /**
     * 获取用户信用信息和月度统计（普通用户专用，无权限）
     */
    @GetMapping("/userStatsOpen")
    public AjaxResult getUserStatsOpen()
    {
        try {
            // 从数据库获取当前用户的真实信用信息
            Long userId = getUserId();
            CreditUserInfo userInfo = creditUserInfoService.selectCreditUserInfoByUserId(userId);
            
            Map<String, Object> userStats = new HashMap<>();
            if (userInfo != null) {
                userStats.put("creditScore", userInfo.getCreditScore());
                userStats.put("creditLevel", getCreditLevel(userInfo.getCreditScore()));
                userStats.put("monthlyGrowth", calculateMonthlyGrowth(userInfo.getSocialScore()));
                userStats.put("totalActivities", getTotalActivities(userId));
                userStats.put("totalPoints", userInfo.getSocialScore());
                userStats.put("ranking", calculateRanking(userInfo.getSocialScore()));
            } else {
                // 如果用户信息不存在，使用默认值
                userStats.put("creditScore", 600);
                userStats.put("creditLevel", "一般");
                userStats.put("monthlyGrowth", 0);
                userStats.put("totalActivities", 0);
                userStats.put("totalPoints", 200);
                userStats.put("ranking", 999);
            }
            
            // 月度增长趋势（模拟数据，实际应该从数据库查询）
            List<Map<String, Object>> monthlyTrend = new ArrayList<>();
            monthlyTrend.add(createMonthlyPoint("1月1日", 5));
            monthlyTrend.add(createMonthlyPoint("1月8日", 8));
            monthlyTrend.add(createMonthlyPoint("1月15日", 12));
            monthlyTrend.add(createMonthlyPoint("1月22日", 7));
            monthlyTrend.add(createMonthlyPoint("1月29日", 10));
            userStats.put("monthlyTrend", monthlyTrend);
            
            return AjaxResult.success(userStats);
        } catch (Exception e) {
            return AjaxResult.error("获取用户统计信息失败：" + e.getMessage());
        }
    }

    /**
     * 获取回收站点列表（普通用户专用，无权限）
     */
    @GetMapping("/recycle/stationsOpen")
    public AjaxResult getRecycleStationsOpen(@RequestParam(required = false) String area)
    {
        CreditRecycleStation queryStation = new CreditRecycleStation();
        queryStation.setIsAvailable("1");
        List<CreditRecycleStation> stations = creditRecycleStationService.selectCreditRecycleStationList(queryStation);
        
        List<Map<String, Object>> result = new ArrayList<>();
        for (CreditRecycleStation station : stations) {
            Map<String, Object> stationMap = new HashMap<>();
            stationMap.put("id", station.getStationId());
            stationMap.put("name", station.getStationName());
            stationMap.put("address", station.getStationAddress());
            stationMap.put("lat", station.getLatitude());
            stationMap.put("lng", station.getLongitude());
            stationMap.put("distance", "1.2km"); // 这里可以根据用户位置计算实际距离
            stationMap.put("types", parseRecycleTypes(station.getRecycleTypes()));
            stationMap.put("openTime", station.getOpenTime());
            stationMap.put("points", Arrays.asList(2, 3, 5, 10)); // 固定积分规则
            stationMap.put("phone", station.getPhone());
            result.add(stationMap);
        }
        
        return AjaxResult.success(result);
    }

    /**
     * 获取回收记录（普通用户专用，无权限）
     */
    @GetMapping("/recycle/recordsOpen")
    public AjaxResult getRecycleRecordsOpen()
    {
        Long userId = getUserId();
        CreditRecycleRecord queryRecord = new CreditRecycleRecord();
        queryRecord.setUserId(userId);
        List<CreditRecycleRecord> records = creditRecycleRecordService.selectCreditRecycleRecordList(queryRecord);
        
        List<Map<String, Object>> result = new ArrayList<>();
        for (CreditRecycleRecord record : records) {
            Map<String, Object> recordMap = new HashMap<>();
            recordMap.put("id", record.getRecordId());
            recordMap.put("date", record.getCreateTime());
            recordMap.put("station", getStationName(record.getStationId()));
            recordMap.put("type", record.getRecycleType());
            recordMap.put("quantity", record.getQuantity());
            recordMap.put("unit", record.getUnit());
            recordMap.put("points", record.getPoints());
            recordMap.put("status", getStatusText(record.getStatus()));
            result.add(recordMap);
        }
        
        return AjaxResult.success(result);
    }

    /**
     * 提交回收记录（普通用户专用，无权限）
     */
    @Log(title = "资源回收提交", businessType = BusinessType.INSERT)
    @PostMapping("/recycle/submitOpen")
    public AjaxResult submitRecycleOpen(@RequestBody Map<String, Object> recycleData)
    {
        Long userId = getUserId();
            Integer stationId = (Integer) recycleData.get("stationId");
            String type = (String) recycleData.get("type");
        Double quantity = Double.valueOf(recycleData.get("quantity").toString());
        String remark = (String) recycleData.get("remark");
            
            // 计算积分
        int points = calculateRecyclePoints(type, quantity);
        
        // 创建回收记录
        CreditRecycleRecord record = new CreditRecycleRecord();
        record.setUserId(userId);
        record.setStationId(stationId.longValue());
        record.setRecycleType(type);
        record.setQuantity(new BigDecimal(quantity));
        record.setUnit(getUnitByType(type));
        record.setPoints(points);
        record.setCarbonReduction(calculateCarbonReduction(type, quantity));
        record.setStatus("confirmed"); // 直接设置为已确认
        record.setRemark(remark);
        record.setCreateBy(getUsername());
        
        int result = creditRecycleRecordService.insertCreditRecycleRecord(record);
        
        if (result > 0) {
            // 更新用户信用分
            CreditUserInfo userInfo = creditUserInfoService.selectCreditUserInfoByUserId(userId);
            if (userInfo != null) {
                Integer currentScore = userInfo.getCreditScore() != null ? userInfo.getCreditScore() : 600;
                Integer newScore = currentScore + points;
                creditUserInfoService.updateCreditScore(userId, newScore, "完成资源回收活动");
            }
            
            // 更新用户统计
            creditProsocialStatsService.updateRecycleStats(userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("recordId", record.getRecordId());
            response.put("points", points);
            response.put("status", "confirmed");
            response.put("message", "回收成功！获得" + points + "积分");
            
            return AjaxResult.success(response);
        } else {
            return AjaxResult.error("提交失败，请稍后重试");
        }
    }

    /**
     * 获取水质监测站点（普通用户专用，无权限）
     */
    @GetMapping("/water/stationsOpen")
    public AjaxResult getWaterStationsOpen()
    {
        try {
            List<Map<String, Object>> stations = new ArrayList<>();
            
            Map<String, Object> station1 = new HashMap<>();
            station1.put("id", 1);
            station1.put("name", "珠江水质监测点A");
            station1.put("location", "珠江大桥南侧");
            station1.put("lat", 23.1048);
            station1.put("lng", 113.2612);
            station1.put("waterQuality", "优");
            station1.put("qualityLevel", 1);
            station1.put("lastUpdate", "2024-01-25 14:30");
            station1.put("distance", "800m");
            station1.put("canReport", true);
            stations.add(station1);
            
            Map<String, Object> station2 = new HashMap<>();
            station2.put("id", 2);
            station2.put("name", "流花湖监测站");
            station2.put("location", "流花湖公园内");
            station2.put("lat", 23.1383);
            station2.put("lng", 113.2584);
            station2.put("waterQuality", "良");
            station2.put("qualityLevel", 2);
            station2.put("lastUpdate", "2024-01-25 15:20");
            station2.put("distance", "1.5km");
            station2.put("canReport", true);
            stations.add(station2);
            
            return AjaxResult.success(stations);
        } catch (Exception e) {
            return AjaxResult.error("获取水质监测站点失败：" + e.getMessage());
        }
    }

    /**
     * 获取护水活动列表（普通用户专用，无权限）
     */
    @GetMapping("/water/activitiesOpen")
    public AjaxResult getWaterActivitiesOpen(@RequestParam(required = false) String type)
    {
        try {
            List<Map<String, Object>> activities = new ArrayList<>();
            
            Map<String, Object> activity1 = new HashMap<>();
            activity1.put("id", 1);
            activity1.put("name", "珠江水质监测志愿者");
            activity1.put("type", "监测");
            activity1.put("description", "参与珠江水质监测，记录水质变化");
            activity1.put("location", "珠江大桥南侧");
            activity1.put("startTime", "2024-02-01 09:00");
            activity1.put("endTime", "2024-02-01 12:00");
            activity1.put("scoreReward", 15);
            activity1.put("maxParticipants", 20);
            activity1.put("currentParticipants", 12);
            activity1.put("status", "1");
            activities.add(activity1);
            
            Map<String, Object> activity2 = new HashMap<>();
            activity2.put("id", 2);
            activity2.put("name", "河岸清洁行动");
            activity2.put("type", "清洁");
            activity2.put("description", "清理河岸垃圾，保护水资源");
            activity2.put("location", "流花湖公园");
            activity2.put("startTime", "2024-02-03 14:00");
            activity2.put("endTime", "2024-02-03 17:00");
            activity2.put("scoreReward", 20);
            activity2.put("maxParticipants", 30);
            activity2.put("currentParticipants", 18);
            activity2.put("status", "1");
            activities.add(activity2);
            
            return AjaxResult.success(activities);
        } catch (Exception e) {
            return AjaxResult.error("获取护水活动列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取公益活动列表（普通用户专用，无权限）
     */
    @GetMapping("/charity/activitiesOpen")
    public AjaxResult getCharityActivitiesOpen(@RequestParam(required = false) String category)
    {
        try {
            List<Map<String, Object>> activities = new ArrayList<>();
            
            Map<String, Object> activity1 = new HashMap<>();
            activity1.put("id", 1);
            activity1.put("name", "关爱留守儿童");
            activity1.put("category", "教育");
            activity1.put("description", "为留守儿童提供教育支持和心理关怀");
            activity1.put("location", "广州市儿童福利院");
            activity1.put("startTime", "2024-02-05 09:00");
            activity1.put("endTime", "2024-02-05 16:00");
            activity1.put("scoreReward", 25);
            activity1.put("maxParticipants", 15);
            activity1.put("currentParticipants", 8);
            activity1.put("status", "1");
            activities.add(activity1);
            
            Map<String, Object> activity2 = new HashMap<>();
            activity2.put("id", 2);
            activity2.put("name", "社区义诊服务");
            activity2.put("category", "医疗");
            activity2.put("description", "为社区居民提供免费健康检查");
            activity2.put("location", "越秀区社区服务中心");
            activity2.put("startTime", "2024-02-08 08:00");
            activity2.put("endTime", "2024-02-08 12:00");
            activity2.put("scoreReward", 30);
            activity2.put("maxParticipants", 10);
            activity2.put("currentParticipants", 6);
            activity2.put("status", "1");
            activities.add(activity2);
            
            return AjaxResult.success(activities);
        } catch (Exception e) {
            return AjaxResult.error("获取公益活动列表失败：" + e.getMessage());
        }
    }

    /**
     * 参与活动（普通用户专用，无权限）
     */
    @Log(title = "参加活动", businessType = BusinessType.INSERT)
    @PostMapping("/activities/joinOpen")
    public AjaxResult joinActivityOpen(@RequestBody Map<String, Object> joinData)
    {
        Long userId = getUserId();
            Integer activityId = (Integer) joinData.get("activityId");
            String activityType = (String) joinData.get("activityType");
            
        logger.info("用户报名参加活动，用户ID：{}，活动ID：{}，类型：{}", userId, activityId, activityType);
        
        try {
            if ("water".equals(activityType)) {
                // 参与护水活动
                CreditWaterActivity waterActivity = creditWaterActivityService.selectCreditWaterActivityByActivityId(activityId.longValue());
                if (waterActivity == null) {
                    return AjaxResult.error("活动不存在");
                }
                
                // 创建参与记录
                CreditWaterActivityParticipant participant = new CreditWaterActivityParticipant();
                participant.setUserId(userId);
                participant.setActivityId(activityId.longValue());
                participant.setParticipationDate(new Date());
                participant.setStatus("confirmed");
                participant.setPointsEarned(waterActivity.getPointsReward());
                String durationStr = waterActivity.getDuration();
                if (durationStr != null && !durationStr.trim().isEmpty()) {
                    try {
                        participant.setActualDuration(new BigDecimal(durationStr.trim()));
                    } catch (Exception e) {
                        participant.setActualDuration(BigDecimal.ZERO);
                    }
                } else {
                    participant.setActualDuration(BigDecimal.ZERO);
                }
                participant.setContribution("参与" + waterActivity.getActivityTitle());
                participant.setCreateBy(getUsername());
                
                int result = creditWaterActivityParticipantService.insertCreditWaterActivityParticipant(participant);
                
                if (result > 0) {
                    // 更新用户信用分
                    CreditUserInfo userInfo = creditUserInfoService.selectCreditUserInfoByUserId(userId);
                    if (userInfo != null) {
                        Integer currentScore = userInfo.getCreditScore() != null ? userInfo.getCreditScore() : 600;
                        Integer newScore = currentScore + waterActivity.getPointsReward();
                        creditUserInfoService.updateCreditScore(userId, newScore, "完成护水活动");
                    }
                    
                    // 更新统计
                    creditProsocialStatsService.updateWaterStats(userId);
                    
                    Map<String, Object> response = new HashMap<>();
                    response.put("registrationId", participant.getParticipantId());
                    response.put("status", "confirmed");
                    response.put("points", waterActivity.getPointsReward());
                    response.put("message", "护水活动参与成功！获得" + waterActivity.getPointsReward() + "积分");
                    
                    return AjaxResult.success(response);
                }
            } else if ("charity".equals(activityType)) {
                // 参与公益活动
                CreditCharityActivity charityActivity = creditCharityActivityService.selectCreditCharityActivityByActivityId(activityId.longValue());
                if (charityActivity == null) {
                    return AjaxResult.error("活动不存在");
                }
                
                // 创建参与记录
                CreditCharityActivityParticipant participant = new CreditCharityActivityParticipant();
                participant.setUserId(userId);
                participant.setActivityId(activityId.longValue());
                participant.setParticipationDate(new Date());
                participant.setStatus("confirmed");
                participant.setPointsEarned(charityActivity.getPointsReward());
                String durationStr = charityActivity.getDuration();
                if (durationStr != null && !durationStr.trim().isEmpty()) {
                    try {
                        participant.setActualDuration(new BigDecimal(durationStr.trim()));
                    } catch (Exception e) {
                        participant.setActualDuration(BigDecimal.ZERO);
                    }
                } else {
                    participant.setActualDuration(BigDecimal.ZERO);
                }
                participant.setContribution("参与" + charityActivity.getActivityTitle());
                Object donationAmountObj = joinData.get("donationAmount");
                if (donationAmountObj instanceof BigDecimal) {
                    participant.setDonationAmount((BigDecimal) donationAmountObj);
                } else if (donationAmountObj instanceof Number) {
                    participant.setDonationAmount(BigDecimal.valueOf(((Number) donationAmountObj).doubleValue()));
                } else if (donationAmountObj instanceof String && !((String)donationAmountObj).trim().isEmpty()) {
                    try {
                        participant.setDonationAmount(new BigDecimal((String)donationAmountObj));
                    } catch (Exception e) {
                        participant.setDonationAmount(BigDecimal.ZERO);
                    }
                } else {
                    participant.setDonationAmount(BigDecimal.ZERO);
                }
                participant.setCreateBy(getUsername());
                
                int result = creditCharityActivityParticipantService.insertCreditCharityActivityParticipant(participant);
                
                if (result > 0) {
                    // 更新用户信用分
                    CreditUserInfo userInfo = creditUserInfoService.selectCreditUserInfoByUserId(userId);
                    if (userInfo != null) {
                        Integer currentScore = userInfo.getCreditScore() != null ? userInfo.getCreditScore() : 600;
                        Integer newScore = currentScore + charityActivity.getPointsReward();
                        creditUserInfoService.updateCreditScore(userId, newScore, "完成公益活动");
                    }
                    
                    // 更新统计
                    creditProsocialStatsService.updateCharityStats(userId);
                    
                    Map<String, Object> response = new HashMap<>();
                    response.put("registrationId", participant.getParticipantId());
                    response.put("status", "confirmed");
                    response.put("points", charityActivity.getPointsReward());
                    response.put("message", "公益活动参与成功！获得" + charityActivity.getPointsReward() + "积分");
                    
                    return AjaxResult.success(response);
                }
            }
            
            return AjaxResult.error("参与失败，请稍后重试");
            
        } catch (Exception e) {
            logger.error("参与活动失败", e);
            return AjaxResult.error("参与失败：" + e.getMessage());
        }
    }

    /**
     * 水质问题上报（普通用户专用，无权限）
     */
    @Log(title = "水质问题上报", businessType = BusinessType.INSERT)
    @PostMapping("/water/reportOpen")
    public AjaxResult reportWaterIssueOpen(@RequestBody Map<String, Object> reportData)
    {
        Long userId = getUserId();
            Integer stationId = (Integer) reportData.get("stationId");
            String issueType = (String) reportData.get("issueType");
            String description = (String) reportData.get("description");
        String urgency = (String) reportData.get("urgency");
        
        logger.info("用户上报水质问题，用户ID：{}，站点ID：{}，问题类型：{}，描述：{}", 
                   userId, stationId, issueType, description);
        
        try {
            // 这里应该创建水质问题上报记录表，暂时用日志记录
            // 计算积分奖励
            int points = 10; // 基础积分
            if ("紧急".equals(urgency)) {
                points = 15;
            } else if ("非常紧急".equals(urgency)) {
                points = 20;
            }
            
            // 更新用户信用分
            CreditUserInfo userInfo = creditUserInfoService.selectCreditUserInfoByUserId(userId);
            if (userInfo != null) {
                Integer currentScore = userInfo.getCreditScore() != null ? userInfo.getCreditScore() : 600;
                Integer newScore = currentScore + points;
                creditUserInfoService.updateCreditScore(userId, newScore, "上报水质问题");
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("reportId", "WR" + System.currentTimeMillis());
            result.put("points", points);
            result.put("status", "submitted");
            result.put("message", "感谢您的上报！相关部门将及时处理，您将获得" + points + "积分奖励");
            
            return AjaxResult.success(result);
            
        } catch (Exception e) {
            logger.error("上报水质问题失败", e);
            return AjaxResult.error("上报失败：" + e.getMessage());
        }
    }

    private String getCreditLevel(Integer creditScore) {
        if (creditScore >= 800) return "优秀";
        else if (creditScore >= 750) return "良好";
        else if (creditScore >= 700) return "中等";
        else if (creditScore >= 650) return "一般";
        else return "较差";
    }
    
    private Integer calculateMonthlyGrowth(Integer socialScore) {
        // 模拟月度增长计算，实际应该从数据库查询历史记录
        return Math.min(socialScore / 10, 50);
    }
    
    private Integer getTotalActivities(Long userId) {
        // 模拟活动数量，实际应该从数据库查询
        return Math.min((int)(userId % 50) + 10, 100);
    }
    
    private Integer calculateRanking(Integer socialScore) {
        // 模拟排名计算，实际应该从数据库查询所有用户排名
        return Math.max(1000 - socialScore, 1);
    }
    
    /**
     * 获取水质等级数值
     */
    private Integer getQualityLevel(String quality) {
        switch (quality) {
            case "优": return 1;
            case "良": return 2;
            case "一般": return 3;
            case "差": return 4;
            default: return 3;
        }
    }
    
    /**
     * 获取护水活动标题
     */
    private String getWaterActivityTitle(Long activityId) {
        CreditWaterActivity activity = creditWaterActivityService.selectCreditWaterActivityByActivityId(activityId);
        return activity != null ? activity.getActivityTitle() : "未知活动";
    }
    
    /**
     * 获取护水活动类型
     */
    private String getWaterActivityType(Long activityId) {
        CreditWaterActivity activity = creditWaterActivityService.selectCreditWaterActivityByActivityId(activityId);
        return activity != null ? activity.getActivityType() : "未知类型";
    }
    
    /**
     * 获取公益活动标题
     */
    private String getCharityActivityTitle(Long activityId) {
        CreditCharityActivity activity = creditCharityActivityService.selectCreditCharityActivityByActivityId(activityId);
        return activity != null ? activity.getActivityTitle() : "未知活动";
    }
    
    /**
     * 获取公益活动分类
     */
    private String getCharityActivityCategory(Long activityId) {
        CreditCharityActivity activity = creditCharityActivityService.selectCreditCharityActivityByActivityId(activityId);
        return activity != null ? activity.getActivityCategory() : "未知分类";
    }
} 